package com.ben.chatroom.common.codec;

import com.ben.chatroom.common.ProInstant;
import com.ben.chatroom.common.entity.ProtoMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author huangyijun
 */
public class ProtobufEncoder extends MessageToByteEncoder<ProtoMsg.Message> {


  @Override
  protected void encode(ChannelHandlerContext ctx, ProtoMsg.Message message, ByteBuf out) throws Exception {
    out.writeShort(ProInstant.MAGIC_CODE);
    out.writeShort(ProInstant.VERSION_CODE);

    byte[] bytes = message.toByteArray();

    int length = bytes.length;

    out.writeInt(length);

    out.writeBytes(bytes);

  }
}
